package com.mcgrobot.plugin.execute.strategy;

import java.net.URLEncoder;
import java.util.ArrayList;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mcgrobot.common.sysenum.EletypeEnum;
import com.mcgrobot.common.sysenum.LogOutTypeEnum;
import com.mcgrobot.common.sysenum.LogTypeEnum;
import com.mcgrobot.common.sysenum.MessageTypeEnum;
import com.mcgrobot.entity.flow.finance.FlowFinance;
import com.mcgrobot.entity.generate.ExecuteStruct;
import com.mcgrobot.entity.generate.RunResult;
import com.mcgrobot.entity.message.FlowBody;
import com.mcgrobot.entity.message.Message;
import com.mcgrobot.plugin.build.McgProduct;
import com.mcgrobot.plugin.execute.ProcessStrategy;
import com.mcgrobot.plugin.websocket.MessagePlugin;
import com.mcgrobot.util.BaiduAuthUtil;
import com.mcgrobot.util.Base64Util;
import com.mcgrobot.util.DataConverter;
import com.mcgrobot.util.HttpUtil;
import com.mcgrobot.util.McgFileUtils;

public class FlowFinanceStrategy implements ProcessStrategy {
	
	private static Logger logger = LoggerFactory.getLogger(FlowFinanceStrategy.class);
	
	@Override
	public void prepare(ArrayList<String> sequence, McgProduct mcgProduct, ExecuteStruct executeStruct)
			throws Exception {
		FlowFinance flowFinance = (FlowFinance)mcgProduct;
		executeStruct.getRunStatus().setExecuteId(flowFinance.getId());
	}

	@Override
	public RunResult run(McgProduct mcgProduct, ExecuteStruct executeStruct) throws Exception {
		FlowFinance flowFinance = (FlowFinance)mcgProduct;
		JSON parentParam = DataConverter.getParentRunResult(flowFinance.getId(), executeStruct);
        Message message = MessagePlugin.getMessage();
        message.getHeader().setMesType(MessageTypeEnum.FLOW);		
        FlowBody flowBody = new FlowBody();
        flowBody.setSubFlag(executeStruct.getSubFlag());
        flowBody.setFlowId(flowFinance.getFlowId());
        flowBody.setOrderNum(flowFinance.getOrderNum());
        flowBody.setLogOutType(LogOutTypeEnum.PARAM.getValue());
        flowBody.setEleType(EletypeEnum.FINANCE.getValue());
        flowBody.setEleTypeDesc(EletypeEnum.FINANCE.getName() + "--》" + flowFinance.getFinanceProperty().getName());
        flowBody.setEleId(flowFinance.getId());
        flowBody.setComment("参数");
        if(parentParam == null) {
        	flowBody.setContent("{}");
        } else {
        	flowBody.setContent(JSON.toJSONString(parentParam, true));
        }
        flowBody.setLogType(LogTypeEnum.INFO.getValue());
        flowBody.setLogTypeDesc(LogTypeEnum.INFO.getName());
        message.setBody(flowBody);
        MessagePlugin.push(flowFinance.getMcgWebScoketCode(), executeStruct.getSession().getId(), message);		
		
		flowFinance = DataConverter.flowOjbectRepalceGlobal(DataConverter.addFlowStartRunResult(parentParam, executeStruct), flowFinance);		
		RunResult runResult = new RunResult();
		runResult.setElementId(flowFinance.getId());
		
		JSONObject runResultJson = (JSONObject)parentParam;
		
		runResultJson.put(flowFinance.getFinanceProperty().getKey(), JSON.parseObject(quotaInvoice(flowFinance.getFinanceProperty().getImgUrl())));
		runResult.setJsonVar(JSON.toJSONString(runResultJson, true));
		executeStruct.getRunStatus().setCode("success");

		logger.debug("账务票据识别控件：{}，执行完毕！执行状态：{}", JSON.toJSONString(flowFinance), JSON.toJSONString(executeStruct.getRunStatus()));
		return runResult;
	}

    public static String quotaInvoice(String imgUrl) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/quota_invoice";
        try {
            // 本地文件路径
            byte[] imgData = McgFileUtils.readFileByBytes(imgUrl);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = BaiduAuthUtil.getAuth();

            String result = HttpUtil.post(url, accessToken, param);
            return result;
        } catch (Exception e) {
        	logger.error("定额发票识别出错：", e);
        }
        return null;
    }
}
